package com.pinkpig.excel.row;

import com.pinkpig.excel.metadata.PrimaryKeyMetaData;
import com.pinkpig.excel.metadata.TableMetaData;
import com.pinkpig.excel.row.model.IndexRowModel;
import com.pinkpig.excel.row.model.RowModel;
import com.sun.deploy.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author vincenfeng
 */
public class IndexRowModelBuilder implements RowModelBuilder<TableMetaData> {

    @Override
    public List<RowModel> build(TableMetaData tableMetaData){
        List<RowModel> indexRowModels = new ArrayList<>();
        //添加主键索引行
        PrimaryKeyMetaData pkMetaData = tableMetaData.getPrimaryKey();
        if(null!=pkMetaData){
            List<String> pkColumnNames = new ArrayList<>();
            pkMetaData.getPkColumns().forEach(c->{
                pkColumnNames.add(c.getColumnName());
            });
            IndexRowModel pkRowModel = new IndexRowModel();
            pkRowModel.setIndexName(pkMetaData.getPkName());
            pkRowModel.setColumnNames(StringUtils.join(pkColumnNames, ","));
            pkRowModel.setIndexType("PRIMARY");
            indexRowModels.add(pkRowModel);
        }
        //添加普通索引行
        if(null!=tableMetaData.getIndexes()){
            tableMetaData.getIndexes().forEach(index->{
                List<String> columnNames = new ArrayList<>();
                index.getIndexColumns().forEach(c->{
                    columnNames.add(c.getColumnName());
                });
                IndexRowModel indexRowModel = new IndexRowModel();
                indexRowModel.setIndexName(index.getIndexName());
                indexRowModel.setColumnNames(StringUtils.join(columnNames, ","));
                indexRowModel.setIndexType(index.isUnique()?"UNIQUE":"NON_UNIQUE");
                indexRowModels.add(indexRowModel);
            });
        }
        return indexRowModels;
    }

}
